﻿using System.Reflection;
using K9Nano.Dependency;
using K9Nano.Exceptions;
using K9Nano.Settings;
using Microsoft.Extensions.DependencyInjection;

namespace K9Nano.Application.Setting;

public class SettingAppService(ISettingManager manager, IServiceProvider serviceProvider) : ISettingAppService, IScopedDependency
{
    /// <summary>
    /// 修改当前用户或者应用全局设置
    /// </summary>
    /// <param name="input"></param>
    /// <param name="cancellation"></param>
    /// <returns></returns>
    public virtual async Task ChangeSettingAsync(SettingChangeInput input, CancellationToken cancellation = default)
    {
        await manager.ChangeSettingAsync(input.Name, input.Value ?? string.Empty, cancellation);
    }

    /// <summary>
    /// 获取设置项分组
    /// </summary>
    /// <returns></returns>
    public virtual IEnumerable<string> GetGroupsForEdit()
    {
        var iocHelper = serviceProvider.GetRequiredService<IIocHelper>();

        var groups = iocHelper.GetRegisteredTypes<ISettingGroupEditHandler>()
            .Select(x => x.GetCustomAttribute<ServiceKeyNameAttribute>())
            .Where(a => a != null)
            .Select(a => a!.Key)
            .ToList();

        return groups;
    }

    public virtual async Task<SettingEditModelGroup?> GetGroupForEditAsync(string groupName, CancellationToken cancellation = default)
    {
        var handler = serviceProvider.GetKeyedService<ISettingGroupEditHandler>(groupName);
        if (handler == null) return null;

        var group = await handler.GetAsync(cancellation);
        return group;
    }

    public virtual async Task ChangeSettingsAsync(SettingEditModelGroupInput input, CancellationToken cancellation = default)
    {
        var handler = serviceProvider.GetKeyedService<ISettingGroupEditHandler>(input.Name);
        if (handler == null) throw FriendlyException.BadRequest($"无法修改设置分组，未定义处理接口：{input.Name}");

        await handler.SaveAsync(input.Settings, cancellation);
    }
}